import { RandomTool } from '@es-tool/core'

export class FileItem {

    public id: string = ''

    public name: string = ''

    public mime: string = ''

    public file: File = {} as any

    public objectUrl: string = ''

    public status: FileItemStatus = '初始化'

    public percent?: number

    public url?: string

    public response?: Record<string, any>


    public constructor() {
        this.clear = this.clear.bind(this)
    }

    public clear() {
        window.URL.revokeObjectURL(this.objectUrl)
    }


    public static ofUri(uri: string): FileItem {
        const item = new FileItem()
        item.file = {} as any
        item.id = uri
        item.mime = ''
        item.name = uri
        item.status = '完成'
        item.url = uri
        item.objectUrl = ''
        item.percent = 1
        item.response = {
            uri,
        }
        return item
    }

    public static ofFile(file: File): FileItem {
        const item = new FileItem()
        item.file = file
        item.id = Date.now() + '_' + RandomTool.randomString(RandomTool.LOWER_CASE_LETTERS, 12)
        item.mime = file.type
        item.name = file.name
        item.status = '初始化'
        item.objectUrl = window.URL.createObjectURL(file)
        return item
    }

}

export type FileItemStatus = '初始化' | '上传中' | '完成' | '错误'
